package Controllers;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;

import Bean.BeanBook;
import Dao.BookDao;
import Impl.BookServiceImpl;
import exception.BookNotFoundException;
import exception.BooksNotFoundException;

/**
 * Servlet implementation class BookRecommendController
 */
@Controller
public class BookRecommendController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    private BookServiceImpl bookService;

    @RequestMapping("/bookrecommend")
    public void handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, BooksNotFoundException, BookNotFoundException {
    	response.setContentType("text/html;charset=UTF-8");  
    	JSONArray arr = new JSONArray();
    	ApplicationContext applicationContext=(ApplicationContext)request.getSession().getServletContext().getAttribute("ctx");
        bookService=(BookServiceImpl)applicationContext.getBean("BookServiceImpl");
        ArrayList<String> bookids;
        
		bookids = bookService.gettop();
		for(int i=0;i<bookids.size();i++) {
			BeanBook book=bookService.getBookDetails(bookids.get(i));
			arr.add(book.toJson());
		}
        response.getWriter().append(arr.toJSONString());
    }

}
